package com.devshephard.jucks.countDown.semphore;

import java.util.concurrent.Semaphore;

//信号量,限流操作
//相当于抢车位，当有新的信号量被获取后，该线程占有该信号量，
//当该线程释放信号量，后面的线程则可以获取到该线程释放的信号量
public class semaphore {

    public static void main(String[] args) {

        //定义三个信号量
        Semaphore semaphore = new Semaphore(3);

        for (int i = 0; i < 6; i++) {
            new Thread(()->{
                try {
                    System.out.println("线程" + Thread.currentThread().getName() + "获取信号量中.....");

                    //获取当前信号量
                    semaphore.acquire();

                    System.out.println("线程" + Thread.currentThread().getName() + "已获取信号量");

                    //睡眠两秒钟后
                    Thread.sleep(1000);


                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    //睡眠两秒钟后，释放信号量
                    System.out.println("线程" + Thread.currentThread().getName() + "释放信号量");
                    semaphore.release();
                }
            },String.valueOf(i)).start();
        }

    }

}
